package com.seu.nic.component.server;

import com.seu.nic.component.coder.DebugDecoder;
import com.seu.nic.component.handler.EchoHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
public class TcpServer {

    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    public void startNettyServer(int port) {

        try {
            new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
//                    .localAddress("58.192.113.63")
//                    .bind(port)
                    .childHandler(
                            new ChannelInitializer<>() {
                                @Override
                                protected void initChannel(Channel ch) {
                                    ch.pipeline()
                                            .addLast(new DebugDecoder(1024))  // 按换行符分帧
                                            .addLast(new StringDecoder(StandardCharsets.UTF_8)) // 字节转字符串
                                            .addLast(new StringEncoder(StandardCharsets.UTF_8))
                                            .addLast(new EchoHandler()); // 使用独立处理器
                                }
                            })
                    .localAddress(new InetSocketAddress("58.192.113.63", 8999))
                    .bind()
                    .addListener((ChannelFutureListener) bindFuture -> {
                        if (bindFuture.isSuccess()) {
                            log.info("Port bound successfully");
                            Channel channel = bindFuture.channel();

                            channel.closeFuture().addListener((ChannelFutureListener) closeFuture -> {
                                log.info("Channel closed");
                                shutdownGracefully();
                            });

                        } else {
                            log.error("Bind failed: " + bindFuture.cause().getMessage());
                            shutdownGracefully();
                        }
                    });
        } catch (Throwable t) {
            log.info(ExceptionUtils.getFullStackTrace(t));
        } finally {
            log.error("startNettyServer finished");
        }
    }

    private void shutdownGracefully() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    public void broadcast(String message) {
        EchoHandler.broadcast(message);
    }
}
